<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addUserDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdTop, vcenter']" v-for="item1 in scope.row.children" :key="item1.id">
              <!-- 一级权限 -->
              <el-col class="bdTop" :span="6">
                <el-tag closable @close="delTag(scope.row, item1.id)" type="parmary">
                  {{ item1.authName }}
                </el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="18">
                <el-row class="vcenter" v-for="item2 in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col class="bdTop" :span="8">
                    <el-tag closable @close="delTag(scope.row, item2.id)" type="success">
                      {{ item2.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col class="bdTop" :span="16">
                    <el-tag
                      type="warning"
                      closable
                      @close="delTag(scope.row, item3.id)"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                    >
                      {{ item3.authName }}
                    </el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <!-- 操作区域 -->
          <template slot-scope="scope">
            <el-button type="primary" size="mini" icon="el-icon-edit" @click="editInfo(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="mini" icon="el-icon-delete" @click="delUser(scope.row.id)">删除</el-button>
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="rightsManage(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 点击添加角色的弹出层 -->
    <el-dialog title="添加角色" :visible.sync="addUserDialogVisible" width="50%" @close="edDialogClose">
      <el-form :model="addUserForm" :rules="addUserRule" ref="form" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="addUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="reviseBtn">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 用户点击编辑图标的弹出层 -->
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <el-form :model="editUserForm" :rules="addUserRule" ref="form" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editUserForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editUserForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editComplete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击分配权限的弹出层 -->
    <el-dialog title="分配权限" :visible.sync="rightsDialogVisible" @close="setRightsDialogClosed" width="30%">
      <!-- tree 组件渲染数据 -->
      <el-tree
        :data="rightsLsit"
        :props="treeProps"
        node-key="id"
        :default-checked-keys="defKeys"
        ref="rightsDialogForm"
        show-checkbox
        default-expand-all
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 所有权限数据
      rightsLsit: [],
      // 默认选中的节点 id 数组
      defKeys: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      addUserDialogVisible: false,
      editDialogVisible: false,
      rightsDialogVisible: false,
      addUserForm: {
        roleName: '',
        roleDesc: ''
      },
      // 用户修改后的表单
      editUserForm: {
        id: '',
        roleName: '',
        roleDesc: ''
      },
      addUserRule: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur' }
        ]
      },
      // 点击分配权限立即获取到角色id
      roleId: ''
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      this.rolesList = res.data
    },
    // 确认添加角色后的处理函数
    reviseBtn() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('roles', this.addUserForm)
        if (res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.addUserDialogVisible = false
        this.getRolesList()
      })
    },
    async editInfo(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) return
      this.editUserForm = res.data
    },
    // 修改完成后点击确定的函数
    editComplete() {
      this.$refs.form.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editUserForm.roleId, {
          roleName: this.editUserForm.roleName,
          roleDesc: this.editUserForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error('修改角色失败!')
        this.editDialogVisible = false
        this.getRolesList()
        this.$message.success('修改角色成功!')
      })
    },
    // 监听用户 关闭 清空表单
    edDialogClose() {
      this.$refs.form.resetFields()
    },
    editDialogClose() {
      this.$refs.form.resetFields()
    },
    async delUser(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') return
      const { data: res } = await this.$http.delete('roles/' + id)
      if (res.meta.status !== 200) return this.$message.error('删除角色失败!')
      this.$message.success('删除角色成功!')
      this.getRolesList()
    },
    async delTag(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消了删除!')
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error('删除权限失败!')
      this.$message.success('删除权限成功')
      role.children = res.data
    },
    // 点击分配权限按钮
    async rightsManage(role) {
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) return
      this.rightsLsit = res.data
      this.getleafKeys(role, this.defKeys)
      this.roleId = role.id
      this.rightsDialogVisible = true
    },
    // 通过递归形式来获取每一节点的id,并保存到 defKeys 数组当中
    getleafKeys(node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach((item) => {
        this.getleafKeys(item, arr)
      })
    },
    // 监听分配权限窗口关闭
    setRightsDialogClosed() {
      this.defKeys = []
    },
    // 设置分配权限的函数
    async setRights() {
      const keys = [...this.$refs.rightsDialogForm.getCheckedKeys(), ...this.$refs.rightsDialogForm.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error('分配权限失败!')
      this.$message.success('分配权限成功!')
      this.getRolesList()
      this.rightsDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 8px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
